<template>
  <view class="cotainer">
    <view class="object">
      <view class="recharge-object">充值用户</view>

      <view class="recharge-people">
        <text>姓名</text>
        <text>{{userInfo.name}}</text>
      </view>
      <view class="divider"></view>
      <view class="recharge-people">
        <text>学/工号</text>
        <text>{{userInfo.account}}</text>
      </view>
    </view>
    <view class="project">
      <view>
        <view class="project-type">
          <text>金额选择</text>
        </view>
        <view class="divider"></view>
      </view>
      <view class="recharge-select">
        <view class="recharge-body">
          <view v-for="(item, index) in number" :key="index"
            :class="['recharge-number', item.selected ? 'selected' : '']" @click="selectPrice(item, index)">
            {{ item.price }}
          </view>
          <view class="recharge-number" v-if="showCustomAmountButton" @click="openCustomAmountModal">
            自定义
          </view>
        </view>
      </view>
      <view>
        <view class="divider"></view>
        <view class="recharge-money">
          <text>实充金额</text>
          <text>{{ select }}</text>
        </view>
        <view class="divider"></view>
        <view class="recharge-way">
          <text>充值方式</text>
          <text>微信</text>
        </view>
      </view>
    </view>
    <button class="btn" @click="confirmRecharge">确认充值</button>

    <!-- Custom Amount Modal -->
    <view v-if="showCustomAmountModal" class="modal">
      <view class="modal-content">
        <text>请输入自定义金额 (最高200):</text>
        <input ref="customAmountInput" type="number" v-model="customAmount" />
        <view class="button-group">
          <button @click="setCustomAmount">确定</button>
          <button class="cancel-btn" @click="closeCustomAmountModal">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>


<script>
  import {
    ajax
  } from '../../utils/request.js';

  export default {
    data() {
      return {
        number: [{
            id: 0,
            price: 5,
            selected: false
          },
          {
            id: 1,
            price: 10,
            selected: false
          },
          {
            id: 2,
            price: 20,
            selected: false
          },
          {
            id: 3,
            price: 30,
            selected: false
          },
        ],
        select: '',
        showCustomAmountModal: false,
        customAmount: '',
        showCustomAmountButton: true,
        userInfo: []
      };
    },
    methods: {
      selectPrice(item, index) {
        this.number.forEach((el) => {
          el.selected = false;
        });
        this.number[index].selected = true;
        this.select = item.price;
      },
      openCustomAmountModal() {
        this.clearSelection();
        this.showCustomAmountModal = true;
        this.$nextTick(() => {
          const inputElement = this.$refs.customAmountInput;
          if (inputElement && inputElement.$el) {
            inputElement.$el.focus();
          } else if (inputElement) {
            inputElement.focus();
          }
        });
      },
      closeCustomAmountModal() {
        this.showCustomAmountModal = false;
        this.customAmount = '';
      },
      setCustomAmount() {
        const amount = parseFloat(this.customAmount);
        
        // 验证是否为负数
        if (amount < 0) {
          uni.showToast({
            title: '金额不能为负数',
            icon: 'none',
          });
          return;
        }
        
        // 验证是否为整数
        if (!Number.isInteger(amount)) {
          uni.showToast({
            title: '金额不能有小数',
            icon: 'none',
          });
          return;
        }
        
        // 验证金额范围
        if (amount > 0 && amount <= 200) {
          this.select = amount;
          this.closeCustomAmountModal();
        } else {
          uni.showToast({
            title: '请输入有效的金额 (1-200)',
            icon: 'none',
          });
        }
      },
      confirmRecharge() {
        const selectedItem = this.number.find((item) => item.selected);
        const rechargeAmount = selectedItem ? (selectedItem.price === '自定义' ? this.select : selectedItem.price) :
          this.select;

        if (!rechargeAmount) {
          uni.showToast({
            title: '请选择充值金额',
            icon: 'none',
          });
          return;
        }

        const token = uni.getStorageSync('token');
        console.log(token);

        uni.login({
          provider: 'weixin',
          success: (res) => {
            if (res.code) {
              console.log('获取到的 code: ' + res.code);

              const userId = uni.getStorageSync('userId');

              ajax('/api/wxpay/coldwatermeterpaywx', 'POST', {
                  code: res.code,
                  total_fee: rechargeAmount,
                  ss_mc: this.userInfo.ss_mc,
                  userId: userId,
                })
                .then((data) => {
                  console.log(data.msg);
                  uni.requestPayment({
                    provider: 'wxpay',
                    timeStamp: String(data.msg.TimeStamp),
                    nonceStr: data.msg.nonce_str,
                    package: "prepay_id=" + data.msg.responseObject.xml
                      .prepay_id._cdata + "",
                    signType: 'MD5',
                    paySign: data.msg.sign,
                    success: function(res) {
                      console.log('success:' + JSON.stringify(res));
                    },
                    fail: function(err) {
                      console.log('fail:' + JSON.stringify(err));
                    },
                  });
                })
                .catch((error) => {
                  console.error('请求失败:', error);
                });
            } else {
              console.log('登录失败！' + res.errMsg);
            }
          },
          fail: function(err) {
            console.log('调用登录接口失败', err);
          },
        });
      },
      clearSelection() {
        this.number.forEach((item) => {
          item.selected = false;
        });
        this.select = '';
      },
      getUserInfo() {
        this.userInfo = uni.getStorageSync('userInfo');

      }
    },
    onLoad(options) {
      this.getUserInfo();
    },
  };
</script>


<style scoped>
  body {
    margin: 0;
  }

  .cotainer {
    display: flex;
    flex-direction: column;
    height: 120vh;
    background: #f0e8e8;
  }

  .object {
    background: #fff;
    padding: 10px;
  }

  .object .recharge-object {
    border-left: 4px solid green;
    padding-left: 10px;
  }

  .object .recharge-people {
    margin: 10px;
    display: flex;
    justify-content: space-between;
  }

  .project {
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 0 10px;
    height: auto;
    justify-content: space-around;
  }

  .project .project-type {
    border-left: 4px solid green;
    padding-left: 10px;
  }

  .project .recharge-select {
    width: 100%;
    height: auto;
  }

  .project .recharge-select .recharge-body {
    display: flex;
    align-items: center;
    margin: 0 auto;
    width: 90%;
    flex-wrap: wrap;
  }

  .project .recharge-select .recharge-body .recharge-number {
    width: 29%;
    height: 50px;
    margin: 5px;
    border: 0.5px solid #e2e0e0;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }

  .selected {
    background-color: rgb(68, 207, 68);
    color: white;
  }

  .project .recharge-money {
    height: 50rpx;
    line-height: 50rpx;
    margin: 10rpx auto;
    display: flex;
    justify-content: space-between;
  }

  .project .recharge-way {
    height: 50rpx;
    line-height: 50rpx;
    margin: 10rpx auto;
    display: flex;
    justify-content: space-between;
  }

  .btn {
    display: flex;
    justify-content: center;
    margin: 10% auto;
    width: 70%;
    border-radius: 5px;
    align-items: center;
    height: 5%;
    background: rgb(68, 207, 68);
    color: #fff;
    box-sizing: border-box;
    cursor: pointer;
  }

  .divider {
    border: 0.5px solid #e2e0e0;
  }

  .modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .modal-content {
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    width: 90%;
    /* 改为 90% 或其他适合的百分比 */
    max-width: 300px;
    text-align: center;
  }

  .modal-content input {
    width: 100%;
    padding: 10px;
    height: 40px;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-sizing: border-box;
    /* 确保 padding 和 border 不超出宽度 */
  }

  .button-group {
    display: flex;
    justify-content: space-between;
  }

  .button-group button {
    width: 48%;
    padding: 10px;
    border: none;
    border-radius: 5px;
    background-color: rgb(68, 207, 68);
    color: #fff;
    cursor: pointer;
  }

  .cancel-btn {
    background-color: #ccc;
  }
</style>
